const axios = require('axios')
const createNodeHelpers = require('gatsby-node-helpers').default
const { paginate } = require('gatsby-awesome-pagination')


exports.sourceNodes = async ({actions}, {apiURL}) => {
  const { createNode } = actions
  let articles = await loadArticles(apiURL)
  const {createNodeFactory, generateNodeId} = createNodeHelpers({typePrefix: 'articles'})
  const createNodeObject = createNodeFactory('list', node => {
    node.id = generateNodeId('list', node.slug) // 手动指定id
    return node
  })
  articles.forEach(article => {
    // createNodeObject(article) 是创建节点
    createNode(createNodeObject(article)) // 是将节点添加到数据层, 根据数据id创建节点id，如果没有id，则只能添加一条数据，所以要提前指定id
  })
}

async function loadArticles (apiURL) {
  let limit = 100
  let offset = 0
  let result = []
  await load()
  async function load () {
    let {data} = await axios.get(`${apiURL}/articles`, {
      params: {limit, offset}
    })
    result.push(...data.articles)
    if (result.length < data.articlesCount) {
      offset += limit
      await load()
    }
  }
  return result
}

exports.createPages = async ({actions, graphql}) => {
  const { createPage } = actions

  let { data } = await graphql(`
    query {
      allArticlesList {
        nodes {
          slug
        }
      }
    }
  `)

  paginate({
    createPage, // The Gatsby `createPage` function
    items: data.allArticlesList.nodes, // An array of objects
    itemsPerPage: 10, // How many items you want per page
    pathPrefix: '/list', // Creates pages like `/blog`, `/blog/2`, etc
    component: require.resolve('../../src/templates/list.js') // Just like `createPage()`
  })
}